package com.solidtrust.app;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.solidtrust.entity.SolidConfig;


@Component
public class ConfigBean {
	
	@PersistenceContext
	private EntityManager em;
	
	private List<SolidConfig> list;
	
	
	public void loadConfig(){
		list = em.createQuery("from SolidConfig", SolidConfig.class).getResultList();
	}
	
	public SolidConfig getConfig(String key){
		for (SolidConfig sc : list) {
			if(sc.getConfigKey().equals(key)){
				return sc;
			}
		}
		return null;
	}
	
	public String getValue(String key){
		for (SolidConfig sc : list) {
			if(sc.getConfigKey().equals(key)){
				return sc.getConfigValue();
			}
		}
		return null;
	}
	
	@Transactional(readOnly = false)
	public void setValue(String key, String value){
		SolidConfig sc = em.find(SolidConfig.class, key);
		if(sc == null){
			sc = new SolidConfig();
			sc.setConfigKey(key);
		}
		sc.setConfigValue(value);
		em.persist(sc);
	}
	
	@Transactional(readOnly = false)
	public void setValue(String key, String value, boolean reload){
		setValue(key, value);
		if(reload){
			loadConfig();
		}
	}

}
